import { readdirSync, statSync } from 'fs'
import { join } from 'path'

interface SidebarItem {
  text: string
  link?: string
  items?: SidebarItem[]
  collapsed?: boolean
}

function generateSidebarItems(dir: string, basePath: string = ''): SidebarItem[] {
  const items: SidebarItem[] = []
  const files = readdirSync(dir)

  files.forEach((file) => {
    const fullPath = join(dir, file)
    const stat = statSync(fullPath)

    if (stat.isDirectory()) {
      // 如果是目录，递归处理
      const subItems = generateSidebarItems(fullPath, join(basePath, file))
      if (subItems.length > 0) {
        items.push({
          text: file,
          items: subItems,
          collapsed: false
        })
      }
    } else if (file.endsWith('.md')) {
      // 如果是 Markdown 文件
      const fileName = file.replace('.md', '')
      // 确保 link 以 / 开头，并移除多余的斜杠
      const link = '/' + join(basePath, fileName).replace(/\\/g, '/').replace(/\/+/g, '/')
      items.push({
        text: fileName,
        link: link
      })
    }
  })

  return items
}

export function generateSidebar(srcPath: string) {
  const sidebar = generateSidebarItems(srcPath)
  return {
    '/': [...sidebar]
  }
}
